package ui.home

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.rememberWindowState
import model.enums.ContentType
import model.enums.MenuItem
import state.ApplicationWindowsState
import theme.EasyChatTheme
import ui.compose.RectIconButton
import ui.create_group.CreateGroupDialog
import ui.home.column1.Head
import ui.home.column1.LeftFunMenu
import ui.home.column1.SettingMenu
import ui.home.column2.message.MessageList
import ui.home.column2.SearchRow
import ui.home.column2.channel_mapping.ChannelMapping
import ui.home.column3.chat.ChatTitleRow
import ui.home.column3.chat.MessageContent
import ui.home.column3.chat.SendMessageInput
import ui.home.column3.notice.FriendNotification
import ui.home.column3.notice.GroupNotification

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun HomeWindow(
    easyChatTheme: MutableState<EasyChatTheme>,
    applicationWindowsState: ApplicationWindowsState,
    close: () -> Unit
) = Window(
    icon = painterResource("icon/ic_logo.svg"),
    transparent = true,//设置为透明窗口
    undecorated = true, //透明窗口必须取消装饰，这样就没默认的窗口标题栏和那些最小化、最大化、关闭什么的了
    onCloseRequest = close,
    title = "E-Chat",
    state = rememberWindowState(width = 990.dp, height = 665.dp, position = WindowPosition(Alignment.Center))
) {
    //rememberCoroutineScope() 是一个用于在 Composable 函数中创建协程作用域
    val coroutineScope = rememberCoroutineScope()
    //创建ViewModel
    val homeViewModel = remember { HomeViewModel(applicationWindowsState, coroutineScope) }
    val windowsCorner = 2.dp//窗口圆角大小
    Surface(
        modifier = Modifier.fillMaxSize()
            .padding(5.dp)
            .shadow(
                elevation = 2.5.dp,
                shape = RoundedCornerShape(windowsCorner + 3.dp),
            ),//窗口阴影样式
        shape = RoundedCornerShape(windowsCorner) //窗口圆角
    ) {
        Box(
            modifier = Modifier.fillMaxSize().background(
                brush = Brush.linearGradient(
                    colors = easyChatTheme.value.homeBgLinearGradient, // 渐变色列表
                    start = Offset(0f, 50f), // 渐变起点（左上角）
                    end = Offset(1000f, 950f) // 渐变终点（右下角），数值可以根据需要调整以改变角度
                )
            )
        ) {
            Row(
                modifier = Modifier.fillMaxSize()
                    .background(
                        brush = Brush.radialGradient(
                            colors = easyChatTheme.value.homeBgRadialGradient, // 渐变色列表
                            center = Offset(130f, 890f),
                            radius = 500f
                        )
                    ),
            ) {
                //column1
                //头像、功能菜单
                Column(
                    modifier = Modifier.fillMaxHeight()
                        .background(
                            brush = Brush.linearGradient(
                                colors = listOf(Color(0x57FFFFFF), Color(0x27FFFFFF), Color(0x00FFFFFF)), // 渐变色列表
                                start = Offset(0f, 1000f), // 渐变起点（左上角）
                                end = Offset(0f, 0f) // 渐变终点（右下角），数值可以根据需要调整以改变角度
                            )
                        )
                ) {
                    Column(
                        modifier = Modifier.padding(top = 30.dp, start = 10.dp, end = 10.dp)
                            .fillMaxHeight().width(40.dp)
                    ) {
                        //头像
                        Head(url = homeViewModel.headUrl)
                        //功能菜单
                        LeftFunMenu(
                            selectItemId = homeViewModel.leftMenuSelected,
                            column3ContentType = homeViewModel.column3ContentType,
                            viewModel = homeViewModel,
                            easyChatTheme = easyChatTheme
                        )
                        Spacer(Modifier.weight(1f))
                        //更多设置菜单
                        SettingMenu(applicationWindowsState)
                    }

                }
                //column2
                //搜索,消息列表，好友列表
                Column(
                    modifier = Modifier
                        .fillMaxHeight()
                        .width(256.dp)
                        .background(
                            color =
                            when (homeViewModel.leftMenuSelected.value) {
                                MenuItem.Chat -> Color(0x11FFFFFF)
                                MenuItem.Friends -> easyChatTheme.value.mainWhite
                            }
                        )//取决于一级菜单和主题
                        .padding(top = 33.dp)
                ) {
                    //搜索
                    SearchRow(
                        text = homeViewModel.searchText,
                        homeViewModel = homeViewModel,
                        easyChatTheme = easyChatTheme
                    ) { homeViewModel.onAddClick() }
                    Spacer(modifier = Modifier.height(15.dp))
                    //如果一级菜单选中的是消息列表
                    if (homeViewModel.leftMenuSelected.value == MenuItem.Chat) {
                        MessageList(
                            modifier = Modifier.fillMaxWidth().weight(1f),
                            messageListItems = homeViewModel.messageList,
                            viewModel = homeViewModel,
                            easyChatTheme = easyChatTheme
                        )
                    } else if (homeViewModel.leftMenuSelected.value == MenuItem.Friends) {//如果一级菜单选中的是好友列表
                        ChannelMapping(
                            modifier = Modifier.fillMaxWidth().weight(1f),
                            tabSelect = homeViewModel.channelMappingTabSelected,
                            friendsMappingItems = homeViewModel.friendsMappingItems,
                            groupMappingItems = homeViewModel.groupMappingItems,
                            column3ContentType = homeViewModel.column3ContentType,
                            homeViewModel = homeViewModel,
                            easyChatTheme=easyChatTheme
                        )
                    }

                }
                //分割线（竖）
                Spacer(modifier = Modifier.fillMaxHeight().width(1.dp).background(color = Color(0x22747A80)))
                //column3
                //聊天框，输入框，群公告，群成员，
                Column(
                    modifier = Modifier
                        .fillMaxHeight()
                        .weight(1f)
                ) {
                    //如果内容类型是好友聊天，群聊
                    if (homeViewModel.column3ContentType.value == ContentType.FriendChat || homeViewModel.column3ContentType.value == ContentType.GroupChat) {
                        Spacer(modifier = Modifier.fillMaxWidth().height(33.dp))
                        ChatTitleRow(homeViewModel.chatTitle,easyChatTheme,applicationWindowsState,homeViewModel)
                        //分割线（横）
                        Spacer(modifier = Modifier.fillMaxWidth().height(1.dp).background(color = Color(0x22747A80)))
                        Row(modifier = Modifier.fillMaxWidth().weight(1f)) {
                            //聊天框，输入框
                            Column(modifier = Modifier.fillMaxHeight().weight(1f)) {
                                MessageContent(
                                    modifier = Modifier.fillMaxWidth().weight(1f),
                                    messageContentItems = homeViewModel.messageContentItemList,
                                    easyChatTheme = easyChatTheme
                                )
                                //分割线（横）
                                Spacer(
                                    modifier = Modifier.fillMaxWidth().height(1.dp)
                                        .background(color = Color(0x22747A80))
                                )
                                SendMessageInput(homeViewModel = homeViewModel, easyChatTheme = easyChatTheme)
                            }
                            //群公告，群成员，如果是群就显示
                            if (homeViewModel.column3ContentType.value == ContentType.GroupChat) {
                                Column { }
                            }
                        }
                    } else if (homeViewModel.column3ContentType.value.equals(ContentType.FriendInformation)) {
                        //好友信息

                    } else if (homeViewModel.column3ContentType.value.equals(ContentType.FriendNotification)) {
                        //好友通知
                        FriendNotification(
                            modifier = Modifier,
                            items = homeViewModel.friendNotificationItems,
                            homeViewModel = homeViewModel,
                            easyChatTheme = easyChatTheme
                        )
                    } else if (homeViewModel.column3ContentType.value.equals(ContentType.GroupNotification)) {
                        //群通知
                        GroupNotification(modifier = Modifier, items = homeViewModel.groupNotificationItems, easyChatTheme = easyChatTheme)
                    } else {
                        //空内容显示logo
                        Box(
                            contentAlignment = Alignment.Center,
                            modifier = Modifier
                                .background(color = easyChatTheme.value.mainColor2)
                                .fillMaxSize()
                        ) {
                            Icon(
                                painter = painterResource("icon/ic_logo.svg"),
                                contentDescription = "logo",
                                tint = easyChatTheme.value.logoNoneContentColor,
                                modifier = Modifier.size(128.dp)
                            )
                        }
                    }
                }
            }
        }

    }

    //窗口可拖动区域，鼠标按住后可以拖动窗口
    WindowDraggableArea {
        Surface(
            modifier = Modifier.fillMaxWidth().height(Dp(33f)).padding(5.dp),
            color = Color.Transparent,
            shape = RoundedCornerShape(windowsCorner, windowsCorner)
        ) {
            val isMouseIn = remember { mutableStateOf(false) }
            Box(contentAlignment = Alignment.TopEnd, modifier = Modifier
                ) {
                RectIconButton(
                    onClick = close,
                    modifier = Modifier.size(30.dp)
                        .background(
                            color = if (isMouseIn.value) Color(0xFFC42B1C)
                            else Color.Transparent
                        ).onPointerEvent(PointerEventType.Enter) { isMouseIn.value = true }
                        .onPointerEvent(PointerEventType.Exit) { isMouseIn.value = false },
                ) {
                    Icon(
                        painter = painterResource("icon/ic_close.svg"),
                        contentDescription = "关闭",
                        tint = if (isMouseIn.value) Color.White else Color.Black,
                        modifier = Modifier.size(33.dp).padding(4.dp)
                    )
                }
            }
        }
    }

    if (homeViewModel.createGroupDialog.value) {
        CreateGroupDialog(easyChatTheme,homeViewModel)
    }
}